/* 单张图片上传 */
<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :http-request="httpRequest"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :accept="accept || 'image/png,image/jpg,image/jpeg'"
    >
      <el-button v-loading.fullscreen.lock="fullscreenLoading" size="mini" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">注:只支持{{ accept || 'image/png,image/jpg,image/jpeg' }}格式类型</div>
    </el-upload>
    <el-image v-if="avatar" style="width: 150px; height: 150px" :src="avatar" :preview-src-list="[avatar]" />
  </div>
</template>

<script>
import { upload } from "@/api/common";
export default {
  props: {
    accept: {
      type: String,
      default: 'image/png,image/jpg,image/jpeg'
    },
    size: {
      type: Number,
      default: 100
    },
    avatar: {
      type: String,
      default: ''
    },
    dataFile: {
      type: Array,
      default: () => null
    }
  },
  data() {
    return {
      fullscreenLoading: false
    }
  },
  methods: {
    httpRequest(e) {
      const data = {}
      const fileType = e.file.type || ''
      const fileArr = fileType.split('/')
      if (fileArr.length > 0) {
        data.type = fileArr[0]
        data.fix = fileArr[1]
      }
      console.log('httpRequest data - %o', data)
      this.$store.dispatch('app/uploadPolice', data).then((res) => {
        console.log('httpRequest uploadPolice - %o', res)
        const formData = res.data
        formData.file = e.file
        this.$store.dispatch('app/uploadToOss', formData).then((res) => {
          if (res.code === 200) {
            this.$message.success('上传成功')
            if (this.dataFile) {
              this.$emit('emitAvatarInput', res.data, this.dataFile)
            } else {
              this.$emit('emitAvatarInput', res.data)
            }
          } else {
            this.$message.success('上传失败')
          }
        })
      })
      this.fullscreenLoading = false
    },
    beforeAvatarUpload(file) {
      this.fullscreenLoading = true
      return this.$elUploadBeforeUpload(file)
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
